/*
 * @Date: 2023-03-10 10:45:38
 * @LastEditors: Zireael 1193875164@qq.com
 * @LastEditTime: 2023-03-24 15:20:55
 * @FilePath: \A19\backend\src\api\Get\ApiGetUserTest.ts
 */
import { ApiCall } from "tsrpc";
import {
  ReqGetUserTest,
  ResGetUserTest,
} from "../../shared/protocols/Get/PtlGetUserTest";
import { Global } from "../../Global/index";
import { ObjectId } from "mongodb";
import { studentAnswer } from "../../shared/types/Answer";

export default async function (call: ApiCall<ReqGetUserTest, ResGetUserTest>) {
  // TODO
  const user = call.currentUser;
  const examOrHomework = call.req.examOrHomework
  const cons: { test?: ObjectId; student?: ObjectId } = {
    // test: call.req.testId,
  };
  if(call.req.testId){
    cons.test = call.req.testId
  }
  if (user.role === "teacher") {
  } else {
    cons.student = user._id;
  }

  const ret = await Global.collection(examOrHomework === 'exam'?"userTests":"userHomework")
    .aggregate([
      {
        $match: cons,
      },
      {
        $lookup: {
          from: "users",
          localField: "student",
          foreignField: "_id",
          as: "studentInfo",
        },
      },
    ])
    .toArray();

  // const ret = await Global.collection("selectCourses")
  //   .aggregate([
  //     {
  //       $match: {
  //           course:call.req.courseId
  //       },
  //     },
  //     {
  //       $lookup: {
  //         from: "users",
  //         localField: "student",
  //         foreignField: "_id",
  //         as: "studentInfo",
  //       },
  //     },
  //     {
  //       $lookup: {
  //         from: "userTests",
  //         localField: "student",
  //         foreignField: "student",
  //         as: "tests",
  //       },
  //     },
  //   ])
  //   .toArray();

  call.succ({
    tests: ret as {
      _id: ObjectId
      student: ObjectId
      test: ObjectId
      submitTime: Date
      answers: Array<studentAnswer>
      score:number
      studentInfo: {
        _id: ObjectId;
        name: string;
        password?: string;
        role: string;
        email: string;
        school: string;
        number: string;
        gender: number;
        portrait: string;
      }[];
    }[],
  });
}
